<?php

namespace App\Admin\Actions\Tree;

use App\Lib\WeApp\WeApp;
use App\Models\Mp\WxMpCustomMenu;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Traits\HasPermissions;
use Dcat\Admin\Tree\AbstractTool;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class SyncToWeWeiXinMp extends AbstractTool
{
    /**
     * @return string
     */
	protected $title = '<i class="fa fa-wechat"></i> 同步到微信';

	public function itemProces(WxMpCustomMenu $menu){
	    if($menu){
	        if(in_array($menu->type, ['click', 'scancode_push', 'scancode_waitmsg', 'pic_sysphoto', 'pic_weixin', 'pic_photo_or_album', 'location_select'])){
                if(_empty_($menu->key)){
                    throw new \Exception($menu->name.': key不能为空');
                }
	            return [
                    'type' => $menu->type,
                    'name' => $menu->name,
                    'key' => $menu->key
                ];
            }else if($menu->type == 'view'){
	            if(_empty_($menu->url)){
	                throw new \Exception($menu->name.': 链接不能为空');
                }
                return [
                    'type' => 'view',
                    'name' => $menu->name,
                    'url' => $menu->url
                ];
            }else if($menu->type == 'media_id'){
                if(_empty_($menu->media_id)){
                    throw new \Exception($menu->name.': media_id不能为空');
                }
                return [
                    'type' => 'media_id',
                    'name' => $menu->name,
                    'media_id' => $menu->media_id
                ];
            }else if(in_array($menu->type, ['article_id', 'article_view_limited'])){
                if(_empty_($menu->article_id)){
                    throw new \Exception($menu->name.': article_id不能为空');
                }
                return [
                    'type' => $menu->type,
                    'name' => $menu->name,
                    'article_id' => $menu->article_id
                ];
            }else if( $menu->type == 'miniprogram'){
                if(_empty_($menu->url)){
                    throw new \Exception($menu->name.': url不能为空');
                }
                if(_empty_($menu->appid)){
                    throw new \Exception($menu->name.': appid不能为空');
                }
                if(_empty_($menu->pagepath)){
                    throw new \Exception($menu->name.': pagepath不能为空');
                }
                return [
                    'type' => 'miniprogram',
                    'name' => $menu->name,
                    'url' => trim($menu->url, '/'),
                    'appid' => $menu->appid,
                    'pagepath' => $menu->pagepath,
                ];
            }
        }
	}

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $weapp = new WeApp('mp');
        if($weapp){
            $mp = $weapp->getMpServicer();
            if($mp){
                try {
                    $buttons = [];
                    WxMpCustomMenu::where('parent_id', 0)->orderBy('order', 'asc')->limit(3)->get()->map(function ($v) use (&$buttons){
                        // 先判断有没有下级
                        $subs = WxMpCustomMenu::where('parent_id', $v->id)->orderBy('order', 'asc')->limit(5)->get();
                        if($subs->isNotEmpty()){
                            $sub_buttons = [];
                            $subs->map(function ($sub) use (&$sub_buttons){
                                $s_subs = WxMpCustomMenu::where('parent_id', $sub->id)->orderBy('order', 'asc')->limit(5)->get();
                                if($s_subs->isNotEmpty()){
                                    $sub_sub_buttons = [];
                                    $s_subs->map(function ($s_sub) use (&$sub_sub_buttons){
                                        $sub_sub_buttons[] = $this->itemProces($s_sub);
                                    });
                                    $sub_buttons[] = [
                                        'name' => $sub->name,
                                        'sub_button' => $sub_sub_buttons
                                    ];
                                }else{
                                    $sub_buttons[] = $this->itemProces($sub);
                                }
                            });
                            $buttons[] = [
                                'name' => $v->name,
                                'sub_button' => $sub_buttons
                            ];
                        }else{
                            $buttons[] = $this->itemProces($v);
                        }
                    });
                    $res = $mp->SyncCustomMenu($buttons);
                    if($res['code'] == 200){
                        return $this->response()
                            ->success('同步成功');
                    }else{
                        return $this->response()->error($res['msg']);
                    }
                }catch (\Exception $e){
                    return $this->response()->error($e->getMessage());
                }

            }
        }
        return $this->response()->warning('错误');
    }

    /**
     * @return string|void
     */
    protected function href()
    {
        // return admin_url('auth/users');
    }

    /**
	 * @return string|array|void
	 */
	public function confirm()
	{
		// return ['Confirm?', 'contents'];
	}

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }
}
